<template>
	<uni-load-more :status="isLoadingStatus" v-if="isLoading" /> <!-- 加载状态组件 -->
	<scroll-view v-else :scroll-top="scrollTop" scroll-y class="category-search-container"
		@scrolltolower="handleScrollToLower" @scroll="handleScroll">
		<!-- 搜索框区域 -->
		<view id="searchBox" class="search-box">
			<uni-easyinput prefixIcon="search" focus placeholder="请输入搜索关键词" v-model="searchKeyword"
				@clear="handleClearSearch" @change="handleSearch"></uni-easyinput>
		</view>
		<!-- 搜索条件区域 -->
		<view class="search-conditions">
			<!-- 标签条件 -->
			<view class="tags-container">
				<view class="tags-scroll">
					<view v-for="(tagItem, index) in queryTagData" :key="index" @click="handleTagSelect(tagItem)"
						:class="{'active': selectedTueryTag.some(item => item.id === tagItem.id)}" class="tag-item">
						{{ tagItem.name }}
					</view>
				</view>
				<view class="tags-badge" @click="toggleTagsPopup">
					<uni-badge :text="selectedTagsBadgeText"></uni-badge>
				</view>
			</view>

			<!-- 查询条件区域 -->
			<view class="query-conditions">
				<!-- 字数条件 -->
				<view class="condition-row">
					<view class="condition-item" @click="handleWordCountSelect(wordCountItem)"
						v-for="(wordCountItem, index) in queryWordCountData" :key="index"
						:class="{'active': wordCountItem.id === selectedQueryWordCount?.id}">
						{{ wordCountItem.name }}
					</view>
				</view>
				<!-- 状态条件 -->
				<view class="condition-row">
					<view class="condition-item" @click="handleStatusSelect(statusItem)"
						v-for="(statusItem, index) in queryStatusData" :key="index"
						:class="{'active': statusItem.id === selectedQueryStatus?.id}">
						{{ statusItem.name }}
					</view>
				</view>

				<!-- 类型条件 -->
				<view class="condition-row">
					<view class="condition-item" @click="handleTypeSelect(typeItem)"
						v-for="(typeItem, index) in queryTypeData" :key="index"
						:class="{'active': typeItem.id === selectedQueryType?.id}">
						{{ typeItem.name }}
					</view>
				</view>
			</view>
		</view>
		<!-- 书籍列表区域 -->
		<view class="books-container">
			<ZfBooks ref="booksRef" :queryParams="queryParams" /> <!-- 书籍列表组件 -->
		</view>
		<!-- 回到顶部按钮 -->
		<view @click="scrollToTop" class="back-to-top">
			<text class="back-to-top-text">回到顶部</text>
		</view>

		<!-- 标签选择弹窗 -->
		<view class="tag-view" v-if="isTagsPopupVisible">
			<view class="tag-popup-header">
				<view class="tag-popup-title">
					标签
				</view>
			</view>
			<view class="tag-popup-content">
				<view v-for="(tagItem, index) in queryTagData" :key="index" @click="handleTagSelect(tagItem)"
					:class="{'active': selectedTueryTag.some(item => item.id === tagItem.id)}" class="tag-popup-item">
					{{ tagItem.name }}
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script lang="ts" setup>
	import { useBooks } from '@/composables'; // 导入书籍列表组合式函数
	import { listThreeCategoryAPI } from '@/services/category'; // 导入分类API
	import { CategoryItem } from '../../types/category'; // 导入分类类型
	import { CategorySearchParams } from '../../types/search'; // 导入搜索参数类型
	import { baseURL, queryStatusOptions, queryWordCountOptions, queryTypeOptions, SearchParams } from '@/utils/config'; // 导入配置
	import { computed, onMounted, ref } from 'vue'; // 导入Vue钩子和工具函数

	/**
	 * 搜索关键词
	 */
	const searchKeyword = ref('');

	/**
	 * 查询条件：标签列表
	 */
	const queryTagData = ref<CategoryItem[]>([]);

	/**
	 * 查询条件：字数列表
	 */
	const queryWordCountData = ref<SearchParams[]>([]);

	/**
	 * 查询条件：状态列表
	 */
	const queryStatusData = ref<SearchParams[]>([]);

	/**
	 * 查询条件：类型列表
	 */
	const queryTypeData = ref<SearchParams[]>([]);

	/**
	 * 选中的标签列表
	 */
	const selectedTueryTag = ref<CategoryItem[]>([]);

	/**
	 * 选中的字数条件
	 */
	const selectedQueryWordCount = ref<SearchParams>();

	/**
	 * 选中的状态条件
	 */
	const selectedQueryStatus = ref<SearchParams>();

	/**
	 * 选中的类型条件
	 */
	const selectedQueryType = ref<SearchParams>();

	/**
	 * 查询参数对象
	 */
	const queryParams = ref<CategorySearchParams>({
		name: searchKeyword.value,
		tagList: selectedTueryTag.value.map(item => item.id),
		wordCount: selectedQueryWordCount.value ? selectedQueryWordCount.value.id : 0,
		status: selectedQueryStatus.value ? selectedQueryStatus.value.id : 0,
		type: selectedQueryType.value ? selectedQueryType.value.id : 0,
	});

	/**
	 * 书籍列表相关引用和方法
	 */
	const { booksRef, onScrollToLower: handleScrollToLower, restartHandleScrollToLower } = useBooks();

	/**
	 * 接收父组件参数
	 */
	const props = defineProps<{
		// 三级分类父ID
		parentId : number
		// 三级分类ID
		threeCategoryId : number
	}>();

	/**
	 * 页面加载状态
	 */
	const isLoading = ref(true);

	/**
	 * 加载状态文本
	 */
	const isLoadingStatus = ref('loading');

	/**
	 * 滚动位置
	 */
	const scrollTop = ref(0);

	/**
	 * 标签弹窗显示状态
	 */
	const isTagsPopupVisible = ref(false);

	/**
	 * 页面挂载时初始化数据
	 */
	onMounted(() => {
		// 初始化查询条件
		initQueryTagData();
		initQueryWordCountData();
		initQueryStatusData();
		initQueryTypeData();

		// 模拟加载延迟
		setTimeout(() => {
			isLoading.value = false;
			isLoadingStatus.value = 'more';
		}, 500);
	});

	/**
	 * 回到顶部
	 */
	const scrollToTop = () => {
		scrollTop.value = 0;
	};

	/**
	 * 处理滚动事件
	 * @param e 滚动事件对象
	 */
	const handleScroll = (e : any) => {
		scrollTop.value = e.detail.scrollTop;
	};

	/**
	 * 处理搜索
	 */
	const handleSearch = () => {
		queryParams.value.name = searchKeyword.value;
		handleScrollToLower(); // 触发分页查询
	};

	/**
	 * 清除搜索关键词
	 */
	const handleClearSearch = () => {
		searchKeyword.value = '';
	};

	/**
	 * 初始化标签数据
	 */
	const initQueryTagData = () => {
		listThreeCategoryAPI(props.parentId).then(res => {
			queryTagData.value = res.data;
			// 选中默认标签
			const threeCategory = queryTagData.value.find(item => item.id === props.threeCategoryId) as CategoryItem;
			handleTagSelect(threeCategory);
		});
	};

	/**
	 * 初始化字数条件数据
	 */
	const initQueryWordCountData = () => {
		queryWordCountData.value = queryWordCountOptions;
		selectedQueryWordCount.value = queryWordCountData.value[0];
		queryParams.value.wordCount = selectedQueryWordCount.value.id;
	};

	/**
	 * 初始化状态条件数据
	 */
	const initQueryStatusData = () => {
		queryStatusData.value = queryStatusOptions;
		selectedQueryStatus.value = queryStatusOptions[0];
		queryParams.value.status = selectedQueryStatus.value.id;
	};

	/**
	 * 初始化类型条件数据
	 */
	const initQueryTypeData = () => {
		queryTypeData.value = queryTypeOptions;
		selectedQueryType.value = queryTypeData.value[0];
		queryParams.value.type = selectedQueryType.value.id;
	};

	/**
	 * 选择字数条件
	 * @param query 字数条件对象
	 */
	const handleWordCountSelect = (query : SearchParams) => {
		selectedQueryWordCount.value = query;
		queryParams.value.wordCount = query.id;
		restartHandleScrollToLower(); // 重新触发分页查询
	};

	/**
	 * 选择状态条件
	 * @param query 状态条件对象
	 */
	const handleStatusSelect = (query : SearchParams) => {
		selectedQueryStatus.value = query;
		queryParams.value.status = query.id;
		restartHandleScrollToLower();
	};

	/**
	 * 选择类型条件
	 * @param query 类型条件对象
	 */
	const handleTypeSelect = (query : SearchParams) => {
		selectedQueryType.value = query;
		queryParams.value.type = query.id;
		restartHandleScrollToLower();
	};

	/**
	 * 选择标签
	 * @param tag 标签对象
	 */
	const handleTagSelect = (tag : CategoryItem) => {
		if (selectedTueryTag.value.some(item => item.id === tag.id)) {
			// 移除已选中的标签
			selectedTueryTag.value = selectedTueryTag.value.filter(
				(item) => item.id !== tag.id
			);
		} else {
			if (selectedTueryTag.value.length >= 3) {
				// 提示最多可选3个标签
				uni.showToast({
					title: '最多可选3个标签',
					icon: 'none'
				});
			} else {
				// 添加标签
				selectedTueryTag.value.push(tag);
			}
		}

		// 更新查询参数
		queryParams.value.tagList = selectedTueryTag.value.map(
			(item) => item.id
		);
		restartHandleScrollToLower();
	};

	/**
	 * 切换标签弹窗显示状态
	 */
	const toggleTagsPopup = () => {
		isTagsPopupVisible.value = !isTagsPopupVisible.value;
	};

	/**
	 * 计算选中标签的数量文本
	 */
	const selectedTagsBadgeText = computed(() => {
		return selectedTueryTag.value.length > 0 ? selectedTueryTag.value.length : '>';
	});
</script>

<style lang="scss">
	// 主容器样式
	.category-search-container {
		display: flex;
		flex-direction: column;
		height: 100vh;

		// 搜索框样式
		.search-box {
			height: 40px;
			display: flex;
			align-items: flex-end;
			justify-content: center;
			width: 100%;
			z-index: 50;
			background-color: white;
			padding: 0 16px;
		}

		// 搜索条件区域样式
		.search-conditions {
			height: 180px;
			display: flex;
			flex-direction: column;
			gap: 20px;
			margin-top: 40px;
			background-color: white;
			border-bottom: 1px solid #f3f4f6;
			z-index: 50;

			// 标签容器样式
			.tags-container {
				height: 40px;
				display: flex;

				// 标签滚动区域
				.tags-scroll {
					overflow-x: auto;
					align-items: center;
					padding-left: 8px;
					margin-top: 8px;
					white-space: nowrap;

					// 标签项样式
					.tag-item {
						display: inline-block;
						padding: 4px;
						margin-left: 12px;
						border-radius: 8px;

						// 激活状态
						&.active {
							font-weight: 700;
							color: #d97706;
							background-color: #fed7aa;
						}
					}
				}

				// 标签数量徽章
				.tags-badge {
					margin-left: 12px;
				}
			}

			// 查询条件区域
			.query-conditions {
				height: 120px;
				display: flex;
				flex-direction: column;
				justify-content: center;

				// 条件行样式
				.condition-row {
					display: flex;
					overflow-x: auto;
					align-items: center;
					padding-left: 8px;
					margin: 8px 0;
					white-space: nowrap;

					// 条件项样式
					.condition-item {
						display: inline-block;
						margin-left: 12px;

						// 激活状态
						&.active {
							font-weight: 700;
							color: #d97706;
						}
					}
				}
			}
		}

		// 书籍容器样式
		.books-container {
			background-color: white;
			height: 100vh;
			padding: 0px 10px;
		}

		// 回到顶部按钮
		.back-to-top {
			position: fixed;
			bottom: 16px;
			right: 16px;
			background-color: #6366f1;
			border-radius: 9999px;
			box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
			z-index: 50;

			// 文本样式
			.back-to-top-text {
				color: white;
			}
		}

		// 标签弹窗样式
		.tag-view {
			position: fixed;
			bottom: 0;
			background-color: white;
			height: 35vh;
			width: 100%;
			border-top: 1px solid #c2c2c2;

			// 弹窗头部
			.tag-popup-header {
				display: flex;
				justify-content: center;
				align-items: center;

				// 标题样式
				.tag-popup-title {
					font-size: 18px;
					color: #1c1917;
					font-weight: 700;
				}
			}

			// 弹窗内容
			.tag-popup-content {
				display: flex;
				flex-wrap: wrap;
				justify-content: center;
				gap: 8px;

				// 弹窗标签项
				.tag-popup-item {
					width: 22%;
					text-align: center;
					padding: 4px;
					border-radius: 8px;
					background-color: #f3f4f6;
					font-size: 14px;

					// 激活状态
					&.active {
						font-weight: 700;
						color: #d97706;
						background-color: #fed7aa;
					}
				}
			}
		}
	}
</style>